package com.lam.framework.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.lam.common.context.ContextHolder;
import com.lam.common.utils.ServletUtils;

/**
 * @author lam
 *
 */
public class HttpServletFilter implements Filter {  
  
	@Override  
    public void doFilter(ServletRequest request, ServletResponse response,  
            FilterChain chain) throws IOException, ServletException {  
    	
    	try {
    		if(request instanceof HttpServletRequest) { 
    			HttpServletRequest httpRequest = (HttpServletRequest)request;
    			if (ServletUtils.isJsonRequest(httpRequest)) {
    				httpRequest = new RepeatableReadRequestWrapper(httpRequest);
    			}
    			HttpServletResponse httpResponse = (HttpServletResponse)response;
    			httpResponse.setHeader("Access-Control-Max-Age", "600");//设置跨域预检的有效时间，10分钟
				ContextHolder.initContext(httpRequest, httpResponse);
			    chain.doFilter(httpRequest, response);    
			}else{
				chain.doFilter(request, response);    
			}
		} finally {
			destroyRequestContext();
		}
    } 
    
    private void destroyRequestContext() {
    	ContextHolder.clearCurrentContext();
    }
  
}  